package com.stlm2.ueditor.upload;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.stlm2.core.AppConfig;
import com.stlm2.ueditor.Image;
import com.stlm2.ueditor.PathFormat;
import com.stlm2.ueditor.define.AppInfo;
import com.stlm2.ueditor.define.BaseState;
import com.stlm2.ueditor.define.FileType;
import com.stlm2.ueditor.define.State;
import com.stlm2.util.Convert;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

public class BinaryUploader {

	public static final State save(HttpServletRequest request,
								   Map<String, Object> conf) {
		FileItemStream fileStream = null;
		boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) != null;

		if (!ServletFileUpload.isMultipartContent(request)) {
			return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
		}

		ServletFileUpload upload = new ServletFileUpload(
				new DiskFileItemFactory());

        if ( isAjaxUpload ) {
            upload.setHeaderEncoding( "UTF-8" );
        }

		try {
			FileItemIterator iterator = upload.getItemIterator(request);

			while (iterator.hasNext()) {
				fileStream = iterator.next();

				if (!fileStream.isFormField())
					break;
				fileStream = null;
			}

			if (fileStream == null) {
				return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
			}

			//String savePath = (String) conf.get("savePath");
			String originFileName = fileStream.getName();
			String suffix = FileType.getSuffixByFilename(originFileName);

			originFileName = originFileName.substring(0,
					originFileName.length() - suffix.length());
			//savePath = savePath + suffix;

			//long maxSize = ((Long) conf.get("maxSize")).longValue();

			if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
				return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
			}

			//savePath = PathFormat.parse(savePath, originFileName);

			//修改保存位置
			//String physicalPath = Image.getRet() + AppConfig.RESOURCE_APP_ROOT + savePath;
			//String physicalPath = (String) conf.get("rootPath") + savePath;

			InputStream is = fileStream.openStream();

			String endpoint = "http://oss-cn-beijing.aliyuncs.com";
			String accessKeyId = "LTAIrLdK8OYw20F7";
			String accessKeySecret = "KfH2x72p6zFxbfKqC3kECzwOwFnHAK";
			String bucketName = "ddw-image";
			OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
			String fileName ;
			fileName = getFileName() + suffix;
			client.putObject(new PutObjectRequest(bucketName, fileName,is,new ObjectMetadata()));



		State storageState =new BaseState(true);
			//storageState.putInfo( "size", targetFile.length() );
			//storageState.putInfo( "title", targetFile.getName() );

			//判断图片宽度超过指定宽度时进行压缩，否则不处理 这个会使超过指定宽带的图片上传后变色
//			File file = new File(physicalPath);
//			BufferedImage image = ImageIO.read(file);
//			if(image.getWidth() > (Integer) conf.get("compressBorder"))
//				Thumbnails.of(physicalPath).width((Integer) conf.get("compressBorder")).toFile(physicalPath);

			is.close();

			if (storageState.isSuccess()) {
				storageState.putInfo("url",fileName);
				storageState.putInfo("type", suffix);
				storageState.putInfo("original", originFileName + suffix);
			}

			return storageState;

		} catch (FileUploadException e) {
			return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
		} catch (IOException e) {
		}
		return new BaseState(false, AppInfo.IO_ERROR);
	}

	private static boolean validType(String type, String[] allowTypes) {
		List<String> list = Arrays.asList(allowTypes);

		return list.contains(type);
	}
	public static String getFileName(){
		String uuid = UUID.randomUUID().toString().replace("-", "");
		String time = Convert.toShortYMDWithNoSplit(new Date());
		return uuid + time;
	}
}
